package org.ikun.security_demo.service;


import org.ikun.security_demo.mapper.UserMapper;
import org.ikun.security_demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserDetailsService, UserDetailsPasswordService {

    @Autowired
    UserMapper userMapper;


    /**
     * 根据用户名查询用户对象
     * @param username //用户登录时输入的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User u = userMapper.loadUserByUsername(username);
        if (u == null){
            //说明用户名不存在
            throw new UsernameNotFoundException("账号不存在");

        }
        return u;
    }

    /**
     * 密码升级的方法
     * @param user
     * @param newPassword
     * @return
     */
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        User u = (User) user;
        u.setPassword(newPassword);
        userMapper.updatePassword(u);
        return u;
    }
}
